#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import logging
import os.path

from concurrent_log_handler import ConcurrentRotatingFileHandler

from conf import CONFIG


class Logger:
    """
    Log type, including output to console, output to file, log file dump.
    This class uses the singleton pattern
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        self._logger = logging.getLogger(self.__class__.__name__)
        self._log_format = logging.Formatter(
            '%(asctime)s-[%(name)s]-[file:%(filename)s:%(lineno)d]-[function:%(funcName)s]-[%(levelname)s]: %(message)s'
            , datefmt='%a, %d %b %Y %H:%M:%S')

    def init_logger(self):
        """
        Set a custom format for log
        :return: self._logger
        """
        self._logger.setLevel(CONFIG.LOGGER_LEVEL)
        self._add_handler()
        return self._logger

    def _add_handler(self):
        """
        Add output stream for log, including console output and file output
        :return: None
        """
        # add console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(CONFIG.LOGGER_LEVEL)
        console_handler.setFormatter(self._log_format)
        self._logger.addHandler(console_handler)
        # create log path
        if not os.path.exists(CONFIG.LOGGER_PATH):
            os.mkdir(CONFIG.LOGGER_PATH, mode=0x644)
        log_file = os.path.join(CONFIG.LOGGER_PATH, CONFIG.LOGGER_FILE_NAME)
        # add file handler
        file_handler = ConcurrentRotatingFileHandler(filename=log_file,
                                                     mode='a',
                                                     maxBytes=CONFIG.LOGGER_BUFFER,
                                                     backupCount=CONFIG.LOGGER_FILE_COUNT,
                                                     encoding="utf-8",
                                                     use_gzip=True)
        file_handler.setLevel(CONFIG.LOGGER_LEVEL)
        file_handler.setFormatter(self._log_format)
        self._logger.addHandler(file_handler)


logger = Logger().init_logger()
